<template>
<div class="orderpdd-list">
    <Form :model="formItem" ref="formItem" :inline="true" action="javascript:void(0)">
        <FormItem>
            <Select v-model="formItem.confirm_status" :style="{'width':'100px'}" clearable placeholder="订单状态">
                <Option value="0">未成交</Option>
                <Option value="1">已成交</Option>
                <Option value="2">已取消</Option>
            </Select>
        </FormItem>
        <FormItem>
            <Select v-model="formItem.order_status" :style="{'width':'100px'}" clearable placeholder="发货状态">
                <Option value="1">待发货</Option>
                <Option value="2">待签收</Option>
                <Option value="3">已签收</Option>
            </Select>
        </FormItem>
        <FormItem>
            <Select v-model="formItem.after_sales_status" :style="{'width':'100px'}" clearable placeholder="售后状态">
                <Option value="0">无售后</Option>
                <Option value="1">有售后</Option>
            </Select>
        </FormItem>
        <FormItem>
            <Select v-model="formItem.remark_tag" :style="{'width':'100px'}" clearable placeholder="标记">
                <Option value="0">全部</Option>
                <Option value="1">红色</Option>
                <Option value="2">黄色</Option>
                <Option value="3">绿色</Option>
                <Option value="4">蓝色</Option>
                <Option value="5">紫色</Option>
            </Select>
        </FormItem>
        <FormItem>
            <Select v-model="formItem.supplier_order_status" :style="{'width':'100px'}" clearable placeholder="供货商发货状态">
                <Option value="0">未发货</Option>
                <Option value="1">已发货</Option>
            </Select>
        </FormItem>
        <FormItem>
            <Input v-model="formItem.key" placeholder="按订单号查找..."></Input>
        </FormItem>
        <FormItem>
            <Input v-model="formItem.tracking_number" placeholder="按快递单号查找..."></Input>
        </FormItem>
        <FormItem>
            <Button type="primary" @click="renderTable('formItem')">查找</Button>
            <Button @click="clearFormItem()">清空条件</Button>
        </FormItem>
    </Form>
    <div class="action-btn">
        <Button size="small" style="margin-right: 8px" type="success" @click="printWaybill()">打印面单</Button>
        <Button size="small" style="margin-right: 8px" type="primary" @click="mTrack()">批量发货</Button>
        <Button size="small" style="margin-right: 8px" type="success" @click="firstTrack()">单条发货</Button>
        <Button size="small" style="margin-right: 8px" type="info" @click="reissueTrack()">补发</Button>
    </div>
    <Table border ref="orderpddlist" max-height="700" :columns="list" :data="tablelist" :loading="dataloading" @on-selection-change="changeData">
        <template slot-scope="{ row }" slot="remark_tag">
            <Tag color="default" v-if="row.remark_tag == '0'">{{ row.remark_tag_name }}</Tag>
            <Tag color="red" v-if="row.remark_tag == '1'">{{ row.remark_tag_name }}</Tag>
            <Tag color="yellow" v-if="row.remark_tag == '2'">{{ row.remark_tag_name }}</Tag>
            <Tag color="green" v-if="row.remark_tag == '3'">{{ row.remark_tag_name }}</Tag>
            <Tag color="blue" v-if="row.remark_tag == '4'">{{ row.remark_tag_name }}</Tag>
            <Tag color="purple" v-if="row.remark_tag == '5'">{{ row.remark_tag_name }}</Tag>
        </template>
        <template slot-scope="{ row }" slot="trade_type">
            <Tag color="geekblue" v-if="row.trade_type == '0'">{{ row.trade_type_name }}</Tag>
            <Tag color="red" v-if="row.trade_type == '1'">{{ row.trade_type_name }}</Tag>
        </template>
        <template slot-scope="{ row }" slot="confirm_status">
            <Tag color="geekblue" v-if="row.confirm_status == '1'">{{ row.confirm_status_name }}</Tag>
            <Tag color="red" v-if="row.confirm_status == '0'">{{ row.confirm_status_name }}</Tag>
            <Tag color="green" v-if="row.confirm_status == '2'">{{ row.confirm_status_name }}</Tag>
        </template>
        <template slot-scope="{ row }" slot="order_status">
            <p><Tag color="red" v-if="row.order_status == '1'">{{ row.order_status_name }}</Tag></p>
            <p><Tag color="blue" v-if="row.order_status == '2'">{{ row.order_status_name }} - {{ row.tracking_number }}</Tag></p>
            <p><Tag color="green" v-if="row.order_status == '3'">{{ row.order_status_name }} - {{ row.tracking_number }}</Tag></p>
        </template>
        <template slot-scope="{ row }" slot="after_status">
            <Tag color="green" v-if="row.after_sales_status == '0'">{{ row.after_status }}</Tag>
            <Tag color="red" v-if="row.after_sales_status != '0'">{{ row.after_status }}</Tag>
        </template>
        <template slot-scope="{ row }" slot="supplier">
            <p v-if="row.supplier_id != 0">{{ row.supplier.suppliername }}</p>
        </template>
        <template slot-scope="{ row }" slot="supplier_staff">
            <p v-if="row.supplier_staff_id != 0">{{ row.supplier_staff.staffname }}</p>
        </template>
        <template slot-scope="{ row }" slot="supplier_order_status">
            <Tag color="geekblue" v-if="row.supplier_order_status == '1'">{{ row.tracking_number }}</Tag>
            <Tag color="red" v-if="row.supplier_order_status == '0'">{{ row.supplier_order_status_name }}</Tag>
        </template>
    </Table>
    <!-- 分页 -->
    <div class="table-page">
        <Page size="small" ref="listPage" :total="pages.total" :current="pages.current" :page-size="pages.size" show-elevator show-total @on-change="changePage"></Page>
    </div>
    <!-- 第一次发货的弹出 -->
    <Drawer :closable="false" :mask-closable="true" :scrollable="true" title="选择物流" width="800" v-model="showFirstTrackModel">
        <Table border ref="ordertrack" :columns="order_track_table" :data="order_track" :loading="loading">
            <template slot-scope="{ row }" slot="status">
                <Tag color="red" v-if="row.row == '0'">已用</Tag>
                <Tag color="geekblue" v-if="row.row != '0'">可用</Tag>
            </template>
            <template slot-scope="{ row }" slot="action">
                <Button type="info" size="small" v-if="row.row != '0'" style="margin-right: 5px;float:left" @click="submitFirstTrack(row.id)">发货</Button>
                <Button type="warning" size="small" v-if="row.row != '0'" style="margin-right: 5px;float:left" @click="submitReissueTrack(row.id)">补发</Button>
            </template>
        </Table>
    </Drawer>
    <!-- 补发 -->
    <Drawer :closable="false" :mask-closable="true" :scrollable="true" title="选择物流" width="600" v-model="showReissueTrackModel">
        <Spin size="large" fix v-if="loading"></Spin>
        <Form :model="track" ref="" label-position="right" :label-width="80" action="javascript:void(0)">
            <FormItem label="物流公司" prop="logistics_id">
                <Select v-model="track.logistics_id" :style="{'width':'240px'}" clearable>
                    <Option v-for="item in logistics" :value="item.logistics_id" :key="item.logistics_id">{{ item.logistics_company }}</Option>
                </Select>
            </FormItem>
            <FormItem label="物流编号" prop="tracking_number">
                <Input v-model="track.tracking_number" placeholder="输入物流编号..."></Input>
            </FormItem>
            <FormItem>
                <Button style="margin-right: 8px" @click="showReissueTrackModel = false">取消</Button>
                <Button type="primary" @click="submitReissueTrackNumber()">提交</Button>
            </FormItem>
        </Form>
    </Drawer>
    <!-- 打印面单 -->
    <Drawer :closable="false" :mask-closable="true" :scrollable="true" title="打印面单" width="600" v-model="showPrintWaybillModel">
        <Spin size="large" fix v-if="loading"></Spin>
        <Form :model="track" ref="" label-position="right" :label-width="80" action="javascript:void(0)">
            <FormItem label="物流公司" prop="logistics_id">
                <Select v-model="track.logistics_id" :style="{'width':'240px'}" clearable>
                    <Option v-for="item in logistics" :value="item.logistics_code" :key="item.logistics_code">{{ item.logistics_company }}</Option>
                </Select>
            </FormItem>
            <FormItem>
                <Button style="margin-right: 8px" @click="showPrintWaybillModel = false">取消</Button>
                <Button type="primary" @click="submitPrintWaybill()">提交</Button>
            </FormItem>
        </Form>
    </Drawer>
</div>
</template>

<script>
import OrderExpand from './OrderExpand.vue';
export default {
    name: 'OrderPdd',
    data() {
        return {
            loading:false,
            dataloading: false,
            specloading:false,
            showSupplierModalStatus:false,
            formItem: {
                'confirm_status':'1',
                'order_status':'1',
                'after_sales_status':'0',
                'remark_tag':'',
                'supplier_order_status' : '0',
                'key': '',
                'tracking_number' : '',
            },
            supplierlist:[],
            shoplist:[],
            pages: {
                current: 1,
                total: 0,
                size: 10
            },
            list: [
                {
                    type: 'selection',
                    width: 60,
                    align: 'center',
                },
                {
                    type: 'expand',
                    width: 50,
                    render: (h, params) => {
                        return h(OrderExpand, {
                            props: {
                                row: params.row
                            }
                        })
                    }
                },
                {
                    title: '订单号',
                    minWidth:220,
                    key: 'order_sn'
                },
                {
                    title: '标记',
                    width: 90,
                    slot: 'remark_tag'
                },
                {
                    title: '订单类型',
                    width: 120,
                    slot: 'trade_type'
                },
                {
                    title: '成交状态',
                    width: 100,
                    slot: 'confirm_status'
                },
                {
                    title: '发货状态',
                    width: 200,
                    slot: 'order_status'
                },
                {
                    title: '售后状态',
                    width: 100,
                    slot: 'after_status'
                },
                {
                    title: '供应商',
                    width: 150,
                    slot: 'supplier'
                },
                {
                    title: '发货人',
                    width: 100,
                    slot: 'supplier_staff'
                },
                {
                    title: '供应商发货状态',
                    width: 180,
                    slot: 'supplier_order_status'
                }
            ],
            tablelist: [],
            selectData:[],
            logistics:[],
            showFirstTrackModel:false,
            track:{
                'logistics_id':'',
                'tracking_number':'',
            },
            showReissueTrackModel:false,
            showPrintWaybillModel:false,
            order_track:[],
            order_track_table:[
                {
                    title: '快递公司编号',
                    width: 150,
                    key: 'logistics_id',
                },
                {
                    title: '物流公司Code',
                    width: 150,
                    key: 'wp_code',
                },
                {
                    title: '快递运单号',
                    width: 200,
                    key: 'tracking_number',
                },
                {
                    title: '状态',
                    width: 100,
                    slot: 'status',
                },
                {
                    title: '操作',
                    slot: 'action',
                    width: 150
                }
            ]
        }
    },
    created: function() {
        // 取数据
        this.getTableList();
        this.$api.logistics.list({ page: 1,'size':10000,'status':1,'type':4}).then(res => {
            if (res.code == 200) {
                this.logistics = res.result.list;
            }
        });
    },
    // 组件
    components: {
        OrderExpand
    },
    methods: {
        clearFormItem:function(){
            this.formItem = {
                'shopid':'',
                'supplier_id':'',
                'confirm_status':'',
                'order_status':'',
                'after_sales_status':'',
                'remark_tag':'',
                'supplier_order_status' : '',
                'key': '',
                'tracking_number':'',
            };
        },
        changePage() {
            this.pages.current = this.$refs['listPage'].currentPage;
            this.getTableList();
        },
        getTableList: function() {
            var params = { page: this.pages.current,'size':this.pages.size,'confirm_status':this.formItem.confirm_status,'order_status':this.formItem.order_status,'after_sales_status':this.formItem.after_sales_status,'remark_tag':this.formItem.remark_tag,'supplier_order_status':this.formItem.supplier_order_status,'tracking_number':this.formItem.tracking_number};
            this.$api.orderpdd.list(params).then(res => {
                this.dataloading = false;
                if (res.code == 200) {
                    this.tablelist = res.result.list;
                    this.pages.total = res.result.total
                    this.$Message.success(res.message);
                }
            });
            return;
        },
        // 筛选
        renderTable: function(name) {
            this.dataloading = true;
            this.pages.currentPage = 1;
            var ps = { 'key': this.formItem.key,'page':1 ,size:this.pages.size,'confirm_status':this.formItem.confirm_status,'order_status':this.formItem.order_status,'after_sales_status':this.formItem.after_sales_status,'remark_tag':this.formItem.remark_tag,'supplier_order_status':this.formItem.supplier_order_status,'tracking_number':this.formItem.tracking_number};
            this.$api.orderpdd.list(ps).then(res => {
                this.dataloading = false;
                if (res.code == 200) {
                    this.tablelist = res.result.list;
                    this.pages.total = res.result.total
                    this.$Message.success(res.message);
                }
            });
            return;
        },
        // 选择订单id
        changeData: function(index) {
            this.selectData = index
        },
        // 发货
        firstTrack:function(){
            if (this.selectData.length != 1) {
                this.$Message.error('请选择一条订单');
                return;
            }else{
                // 拿到所有可以用的面单号
                this.loading = true;
                var order_ids = [];
                this.selectData.forEach((item, index) => {
                    order_ids.push(item.id);
                })
                this.$api.orderpdd.pddordertrack({'order_id':order_ids[0]}).then(res => {
                    if (res.code == 200) {
                        this.order_track = res.result
                        this.showFirstTrackModel = !this.showFirstTrackModel;
                        this.$Message.success(res.message);
                    }
                    this.loading = false;
                }).finally(res => {
                    this.loading = false;
                });
            }
        },
        submitFirstTrack:function(order_track_id){
            this.loading = true;
            this.$api.orderpdd.pddtrack({'order_id':order_ids[0],'order_track_id':order_track_id}).then(res => {
                console.log(res)
                if (res.code == 200) {
                    // this.getTableList();
                    // this.showSupplierModalStatus = !this.showSupplierModalStatus;
                }
                this.loading = false;
            }).finally(res => {
                this.loading = false;
            });
        },
        mTrack:function(){
            this.loading = true;
            var order_ids = [];
            this.selectData.forEach((item, index) => {
                order_ids.push(item.id);
            })
            this.$api.orderpdd.pddtrackm({'order_id':order_ids}).then(res => {
                if (res.code == 200) {
                    this.getTableList();
                    this.$Message.success(res.message);
                }
                this.loading = false;
            }).finally(res => {
                this.loading = false;
            });
        },
        // 补发
        reissueTrack:function(){
            if (this.selectData.length != 1) {
                this.$Message.error('请选择一条订单');
                return;
            }else{
                this.showReissueTrackModel = !this.showReissueTrackModel;
                this.track = {
                    'logistics_id':'',
                    'tracking_number':'',
                };
                this.loading = false;
            }
        },
        submitReissueTrack:function(order_track_id){
            this.loading = true;
            this.$api.orderpdd.pddreissue({'order_id':order_ids[0],'order_track_id':order_track_id}).then(res => {
                console.log(res)
                if (res.code == 200) {
                    // this.getTableList();
                    // this.showSupplierModalStatus = !this.showSupplierModalStatus;
                }
                this.loading = false;
            }).finally(res => {
                this.loading = false;
            });
        },
        submitReissueTrackNumber:function(){
            this.loading = true;
            var order_ids = [];
            this.selectData.forEach((item, index) => {
                order_ids.push(item.id);
            })
            if (order_ids.length > 1) {
                this.$Message.error('只能单条补发');
                return;
            }else{
                this.$api.orderpdd.pddreissue({'order_id':order_ids[0],'logistics':[{'logistics_id':this.track.logistics_id,'tracking_number':this.track.tracking_number}]}).then(res => {
                    console.log(res)
                    if (res.code == 200) {
                        // this.getTableList();
                        // this.showSupplierModalStatus = !this.showSupplierModalStatus;
                    }
                    this.loading = false;
                }).finally(res => {
                    this.loading = false;
                });
            }
        },
        // 打印面单
        printWaybill:function(){
            if (this.selectData.length != 1) {
                this.$Message.error('请选择一条订单');
                return;
            }else{
                this.showPrintWaybillModel = !this.showPrintWaybillModel;
                this.track = {
                    'logistics_id':'',
                    'tracking_number':'',
                };
                this.loading = false;
            }
        },
        submitPrintWaybill:function () {
            this.loading = true;
            var order_ids = [];
            this.selectData.forEach((item, index) => {
                order_ids.push(item.id);
            })
            this.$api.orderpdd.pddwaybill({'order_id':order_ids[0],'wp_code':this.track.logistics_id}).then(res => {
                if (res.code == 200) {
                    // this.getTableList();
                    // this.showSupplierModalStatus = !this.showSupplierModalStatus;
                    // 开始打印
                    let waybill = res.result.waybill;
                    // waybill.forEach(item => {
                    //     console.log(JSON.parse(item.print_data))
                    // })
                    // 创建WebSocket 对象
                    var ws = new WebSocket("wss://127.0.0.1:18653");
                    // 发送打印数据协议(print)
                    ws.onopen = function () {
                        // 开始循环打印
                        waybill.forEach(item => {
                            //请求参数
                            console.log(item)
                            print_data = JSON.parse(item.print_data)
                            // var param = { "cmd": 'getPrinters', "requestID": "123458976", "version": "1.0" }
                            var param = {
                                "ERPId": item.object_id,
                                "cmd": "print",
                                "requestID": item.object_id,
                                "task": {
                                    "documents": [
                                        {
                                            "contents": [
                                                {
                                                    "encryptedData": print_data.encryptedData,
                                                    "signature": print_data.signature,
                                                    "templateUrl": print_data.templateUrl,
                                                    "ver": print_data.ver,
                                                    "userid": res.result.userid,
                                                }
                                            ],
                                            "documentID":  item.waybill_code
                                        }
                                    ],
                                    "notifyType": [
                                        "print"
                                    ],
                                    "preview": false,
                                    "previewType": "image",
                                    "printer": "",
                                    "taskID": item.object_id
                                },
                                "version": "1.0"
                            }
                            // 使用 send() 方法发送数据 ;
                            // console.log(param)
                            ws.send(JSON.stringify(param));
                        });
                        // alert("数据发送中...");
                    }
                    //接收到服务端响应的数据时，触发事件
                    ws.onmessage = function (evt) {
                        var data = evt.data;
                        console.log(evt)
                        console.log(data)
                        // 收到正常反馈以后断开连接
                        ws.close();
                    }
                    // 断开 web socket 连接成功触发事件
                    ws.onclose = function () {
                        this.$Message.success('打印完成...');
                    };

                }
                this.loading = false;
            }).finally(res => {
                this.loading = false;
            });
        }
    }
}
</script>
